﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DAL;
using CommontLibrary;
public partial class admin_insertUser : WebBaseUserControl
{
#region "Member variables"
    private int intUserID = 0;
    private int intUserID1 = 0;
    bool boolRead = false;
    bool boolWrite = false;
    bool boolUpdate = false;
    bool boolDelete = false;
    int intnguoidungcaptren = 0;
    DANguoidung objNguoidung;
    DAQuyen objQuyen;
    DALog objLog;
#endregion
#region "Parametter variables"
    // Ham lay Bind du lieu
    public SqlConnection ConnectionView
    {
        get
        {
            object obj2 = this.ViewState["ConnectionView"];
            if (obj2 != null)
            {
                return (SqlConnection)obj2;
            }
            return null;
        }
        set
        {
            this.ViewState["ConnectionView"] = value;
        }
    }
    #endregion
#region "Private methods"   
    // Lay tat ca cac du lieu cua bang User theo ngon ngu
	private void loadNguoidung()
    {

        DataSet dsNguoidung = objNguoidung.loadNguoidung(txtFullName.Text.Trim(),txtUserName.Text.Trim());
        BindData.bindGridView(this.grvUser, dsNguoidung);

		//showDatagrid(false);
	}
    // Lay tat ca cac du lieu cua bang Quyen theo ngon ngu
    private void loadNhomID(DropDownList ddlTemp)
    {
        DataSet dsQuyen = objQuyen.loadQuyen();
        if (dsQuyen != null && dsQuyen.Tables[0].Rows.Count > 0)
        {
            DataRow[] drs = dsQuyen.Tables[0].Select("NhomID = 0");
            ddlTemp.Items.Clear();
            foreach (DataRow dr in drs)
            {
                ListItem liTemp = new ListItem();
                liTemp.Text = " " + dr["Tennhom"].ToString();
                liTemp.Value = dr["ID"].ToString();
                ddlTemp.Items.Add(liTemp);
                loadNhomIDSub(ddlTemp, dr["ID"].ToString(), dsQuyen.Tables[0], " ---");
            }
            ddlTemp.Visible = true;
        }
        else
        {
            ddlTemp.Visible = false;
        }
    }
    private void loadNhomIDSub(DropDownList ddlTemp, string strCheck, DataTable dt, string strPath)
    {
        DataRow[] drs = dt.Select("NhomID =" + strCheck);
        foreach (DataRow dr in drs)
        {
            ListItem liTemp = new ListItem();
            liTemp.Text = strPath + dr["Tennhom"].ToString();
            liTemp.Value = dr["ID"].ToString();
            ddlTemp.Items.Add(liTemp);
            loadNhomIDSub(ddlTemp, dr["ID"].ToString(), dt, strPath + "---");
        }
    }
    //check validation
    private bool checkValidation()
    {
        string strUserName = this.txtUserName.Text.Trim();
        string strPassWord = this.txtPassWord.Text.Trim();      
        if (strUserName.Equals(""))
        {
            this.ctvUserName.IsValid = false;
            return false;
        }
        else
        {
            return true;
        }
    }
    //check validation
    private bool check_exist_user()
    {
        string strUserName = this.txtUserName.Text.Trim();       

        return true;
    }
    //Reset text cua from    
    private void resetFrom()
    {
        this.txtUserName.Text = "";
        this.txtPassWord.Text = "";
        this.txtRePassWord.Text = "";
        this. txtFullName.Text = "";
    }
    //Delete QuyenNguoiDUng
    private void DeleteQuyenLevel()
    {
        
        int intCheck = objNguoidung.removeQuyenNguoiDung(intUserID);
        if (intCheck > 0)
        {
            this.lblMess.Text = "";
        }

        else
        {
            this.lblMess.Text = "Lỗi trong quá trình xóa bản ghi!";
        }
    }
	// Tao moi tai khoan
    // Chỉnh sửa by LinhDH 10/04/2012
	private void CreateUserAccount()
	{
        if (Page.IsValid)
        {
            if (checkValidation())
            {
                 string strUserName = this.txtUserName.Text.Trim();
                 if (!objNguoidung.check_trung_username(strUserName))
                 {
                     string v_str_script = "";
                     v_str_script = "<script type='text/javascript'>alert('Username đã tồn tại trong hệ thống !')</script>";
                     if (!Page.ClientScript.IsStartupScriptRegistered("oncheck"))
                         Page.ClientScript.RegisterStartupScript(this.GetType(), "oncheck", v_str_script);
                     return;
                 }
                //string strUserName = this.txtUserName.Text.Trim();
                string strPassWord = this.txtPassWord.Text.Trim();
                string FullName = this.txtFullName.Text;
                strPassWord = FormsAuthentication.HashPasswordForStoringInConfigFile(strPassWord, "SHA1");
                int intnhomID = Convert.ToInt32(this.ddlNhomID.SelectedValue);
                int intChẹck = objNguoidung.insertNguoidung(strUserName, strPassWord, FullName);
                if (intChẹck > 0)
                {
                   // DeleteQuyenLevel();
                    int intChẹckUserRole = objNguoidung.insertQuyenNguoiDung(intChẹck, intnhomID, intnguoidungcaptren);
                    if (intChẹckUserRole > 0)
                    {
                        this.lblMess.Text = "Thêm bản ghi thành công";
                        Session["UserID"] = intUserID1;
                        objLog.insertLog(0, 0, 10, intUserID1);
                        resetFrom();
                        loadNguoidung();
                    }
                    else
                    {
                        this.lblMess.Text = "Bản ghi này đã có trong dữ liệu!";
                        resetFrom();
                        loadNguoidung();
                    }

                }
                else
                {
                    this.lblMess.Text = "Lỗi trong quá trình thêm mới bản ghi!";
                }
            }
        }
	}
	private void showDatagrid(bool boolVisible)
	{
		grvUser.Columns[2].Visible = boolVisible;
		grvUser.Columns[4].Visible = boolVisible;
	}
	// Xóa tai khoan nguoi dung
    private void DeleteNguoidung(object source, System.Web.UI.WebControls.GridViewDeleteEventArgs e) 
	{
		int intUserid = Convert.ToInt32(grvUser.DataKeys[e.RowIndex].Value);
        if (intUserid != 1)
        {
            int intChẹck = objNguoidung.removeUser(intUserid);
            if (intChẹck > 0)
            {
                this.lblMess.Text = "Xóa thành công bản ghi";
                Session["UserID"] = intUserID1;
                objLog.insertLog(0, intUserid, 9, intUserID1);
                this.btnUpdate.Visible = false;
                loadNguoidung();
            }
            else
            {
                this.lblMess.Text = "Lỗi trong quá trình xóa bản ghi!";
            }
        }
        else
        {
            this.lblMess.Text = "Lỗi trong quá trình xóa bản ghi!";
        }
	}
	// Sua tai khoan nguoi dung
	private void UpdateUserAccount() 
	{
            int intUserid = Convert.ToInt32(this.hdfUserID.Value);
            string strUserName = this.txtUserName.Text.Trim();
            string strPassWord = this.txtPassWord.Text.Trim();
            string FullName = this.txtFullName.Text;
            if (strPassWord == "")
            {
                DataRow dr = objNguoidung.loadNguoidungID(intUserid);
                strPassWord = dr["MatKhau"].ToString();
            }
            else
            {
                // ma hoa mat khau
                strPassWord = FormsAuthentication.HashPasswordForStoringInConfigFile(strPassWord, "SHA1");
            }
            int intnhomID = Convert.ToInt32(this.ddlNhomID.SelectedValue);
            int intChẹck = objNguoidung.updateNguoidung(intUserid, strUserName, strPassWord, FullName);
            if (intChẹck > 0)
            {
                int intChẹckUserRole = objNguoidung.updateQuyenNguoiDung(intUserid, intnhomID);
                this.lblMess.Text = "Sửa bản ghi thành công!";
                Session["UserID"] = intUserID1;
                objLog.insertLog(0, intUserid, 8, intUserID1);
                this.btnUpdate.Visible = false;
                this.btnInsert.Visible = true;
                loadNguoidung();
                resetFrom();                
            }
            else if (intChẹck == 0)
            {
                this.lblMess.Text = "Tên đăng nhập đã tồn tại trong CSDL";
                loadNguoidung();
                resetFrom();
            }
            else
            {
                this.lblMess.Text = "Lỗi trong quá trình cập nhật!";
                //resetFrom();
                this.btnInsert.Visible = false;
            }
	}
    // Lay tat ca cac du lieu cua bang Role theo ngon ngu cho vao DropDownList trong DataGrid
    private void loadUserUpdate(int intIndexDatagrid)
    {
        int myintUser = Convert.ToInt32(grvUser.DataKeys[intIndexDatagrid].Value);
        DataRow drUserRole = objNguoidung.loadNguoidungID(myintUser);
        this.txtUserName.Text = drUserRole["TenDangNhap"].ToString().Trim();     
        this.hdfUserID.Value = myintUser.ToString();       
        this.txtFullName.Text = drUserRole["HoTen"].ToString().Trim();
        DataSet dsQuyen = objNguoidung.loadQuyenNguoidungbyNguoiDung(myintUser);
        int intnhomid=Convert.ToInt32(dsQuyen.Tables[0].Rows[0]["QuyenID"].ToString());
        if (intnhomid > 0)
        {
            BindData.selectDropDowList(this.ddlNhomID, dsQuyen.Tables[0].Rows[0]["QuyenID"].ToString());
            this.ddlNhomID.Enabled = true;
        } 
    }
#endregion
#region "Events handle"
    //Check quyen han su dung
    private void CheckUserModule(int UserID, int ModuleID)
    {
        //objNguoidung.CheckUserModule(UserID, ModuleID, ref boolRead, ref boolWrite
        //                            , ref boolUpdate, ref boolDelete);
        //if (!boolRead)
        //{
        //    this.btnInsert.Visible = false;
        //    this.grvUser.Visible = false;
        //}
        //if (!boolWrite)
        //{
        //    this.btnInsert.Visible = false;
        //}
        //if (!boolUpdate)
        //{          
        //    this.grvUser.Columns[5].Visible = false;
        //    this.btnRemove.Visible = false;
        //}
        //if (!boolDelete)
        //{
        //    this.grvUser.Columns[4].Visible = false;
        //    this.grvUser.Visible = true;
        //}
        //else
        //{
        //    this.grvUser.Visible = true;
        //}
    }
    private void loadDataAccess()
    {
        SqlConnection sqlConnec = ConnectData.getConnection();      
        objNguoidung = new DANguoidung(sqlConnec);
        objQuyen = new DAQuyen(sqlConnec);
        objLog = new DALog(sqlConnec);
    }
    //Main load
    protected void Page_Load(object sender, EventArgs e)
    {
       
            // Put user code to initialize the page here
            intUserID = Convert.ToInt32(Session["UserID"].ToString().Trim());          
            loadDataAccess();
            loadNhomID(this.ddlNhomID);
            loadNguoidung();      
            if (!Page.IsPostBack)
            {                       
                this.btnUpdate.Visible = false;
            }
    }

    // Su kien them moi tai khoan
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        try
        {
            this.lblMess.Text = "";
            CreateUserAccount();
        }
        catch (Exception v_e)
        {
            
            throw v_e;
        }

    }
    //Su kien sua tai khoan
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            this.lblMess.Text = "";
            UpdateUserAccount();
        }
        catch (Exception v_e)
        {

            throw v_e;
        }

    }
    // Su kien dat lai form 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        try
        {
            this.lblMess.Text = "";
            resetFrom();
        }
        catch (Exception v_e)
        {

            throw v_e;
        }

    }
    //Su kien bind du lieu form User
    protected void grvUser_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.DataItem != null)
                {
                    e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
                    e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";// Modify
                    // Modify
                    ImageButton lbtDeleteTemp = ((ImageButton)e.Row.FindControl("lbtDelete"));
                    if (lbtDeleteTemp != null)
                    {
                        string strDelete = "Bạn chắc chắn muốn xóa OK , Bạn hủy lệnh CANCEL ";
                        lbtDeleteTemp.Attributes.Add("Onclick", "javascript:if(confirm('" + strDelete + "')) {return true} else {return false};");
                    }
                }
            }
        }
        catch (Exception v_e)
        {

            throw v_e;
        }

    }
    //Su kien xoa tai khoan
    protected void grvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            grvUser.EditIndex = -1;
            this.lblMess.Text = "";
            DeleteNguoidung(sender, e);	
        }
        catch (Exception v_e)
        {

            throw v_e;
        }

    }
    // Su kien su ly nut Edit trong DataGrid
    protected void grvUser_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            this.btnUpdate.Visible = true;
            this.btnInsert.Visible = false;
            this.lblMess.Text = "";
            loadUserUpdate(e.NewEditIndex);	
        }
        catch (Exception v_e)
        {

            throw v_e;
        }
	
    }
    protected void grvUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            this.grvUser.EditIndex = -1;
            this.grvUser.PageIndex = e.NewPageIndex;
            loadNguoidung();
        }
        catch (Exception v_e)
        {

            throw v_e;
        }

    }
    protected void btnTimKiem_Click(object sender, EventArgs e)
    {
        try
        {
            this.grvUser.DataSource = null;
            grvUser.DataBind();
            loadNguoidung();
        }
        catch (Exception v_e)
        {

            throw v_e;
        }
    }
#endregion

   
}
